package com.xiyuan.smartutils.client.http;

/**
 * HTTP结果信息，用于把状态码和描述重新组装成一个对象返回
 *
 * @version v1.0.0 @author lgz 2017-9-21 新建与整理
 */
public class HttpResult {
    private int responseStatus;
    private String responseText;
    
    private byte[] responseBytes;
    private Exception exception;
    
    public HttpResult(int responseStatus, String responseText) {
        this.responseStatus = responseStatus;
        this.responseText = responseText;
    }
    
    public HttpResult(int responseStatus, String responseText, byte[] responseBytes) {
        this.responseStatus = responseStatus;
        this.responseText = responseText;
        this.responseBytes = responseBytes;
    }
    
    /**
     * 获取状态码
     */
    public int getResponseStatus() {
        return responseStatus;
    }
    
    /**
     * 获取状态信息或响应内容
     */
    public String getResponseText() {
        return responseBytes == null ? responseText : (responseText = new String(responseBytes));
    }
    
    /**
     * 获取状态信息或响应字节
     */
    public byte[] getResponseBytes() {
        return responseBytes != null ? responseBytes.clone() : responseText == null ? null : responseText.getBytes();
    }
    
    /**
     * 判断是否成功
     */
    public boolean isHttpOK() {
        return this.responseStatus == 200;
    }
    
    public Throwable getException() {
        return exception;
    }
    
    public boolean isException() {
        return exception != null;
    }
    
    protected final HttpResult setException(Exception exception) {
        this.exception = exception;
        return this;
    }
    
    /**
     * 判断是否请求异常，如果请求异常则抛异常，
     * @throws Exception 异常信息
     */
    public HttpResult getThisTryThrow() throws Exception {
        if(exception != null) throw exception;
        return this;
    }
   
}
